from server.models import account
from django.db.models.query_utils import Q
from random import random

# Create your views here.
def checkAccount(title, password):
    es = account.objects.filter(title=title)
    if es.exists() != True:
        return 2
    for e in es:
        if e.password==password:
            return 0
    return 1

def doRegister(username, password, email):
    es = account.objects.filter(title=username)
    if es.exists():
        return 1
    else:
        user = account.objects.create(title = username, password=password, email=email)
        user.save()
        return 0
    
def getAllAccount():
    Accounts = []
    es = account.objects.all()
    for e in es:
        Accounts.append({'name':e.title, 'password':e.password})
    return Accounts

def searchAccount(title, email, phone):
    Accounts = []
    es = account.objects.filter(Q(title__contains=title)|Q(email=email)|Q(phone=phone)).order_by("-title")
    if es.exists() != True:
        return Accounts
    for e in es:
        Accounts.append({'title':e.title, 'email':e.email, 'phone':e.phone})
    return Accounts

def randomSelect(accounts):
    amount = accounts.__len__()
    if amount == 0:
        return None
    random_number = random.randint(0, amount-1)
    return accounts[random_number]